package com.chanzany.prototype.deepClone;

import java.io.*;

public class DeepPrototype implements Serializable, Cloneable {

	private static final long serialVersionUID = 1L;

	public String name;

	public DeepCloneableTarget deepCloneableTarget; //引用类型

	public DeepPrototype() {
	}

	//深拷贝--方式1 重写clone方法
	@Override
	protected Object clone() throws CloneNotSupportedException {
        //完成对基本数据类型的克隆
        DeepPrototype deep = (DeepPrototype) super.clone();
        // 完成对引用类型的克隆
        assert deep != null;
        deep.deepCloneableTarget = (DeepCloneableTarget) deep.deepCloneableTarget.clone();
		return deep;
	}

    //深拷贝--方式2 通过对象序列化实现（推荐）
	public Object deepClone() {
	    //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally{
            try {
                assert bos != null;
                bos.close();
                assert oos != null;
                oos.close();
                assert bis != null;
                bis.close();
                assert ois != null;
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
}
